﻿using System.Linq.Expressions;
using Castle.Components.DictionaryAdapter;
using Microsoft.EntityFrameworkCore;
using SBlogCore.Common.DatabaseAccessor.Entitys;

namespace SBlogCore.Common.DatabaseAccessor.Repositorys.EFCore
{
    public partial class Repository<TEntity> where TEntity : class, IBaseEntity
    {
        /// <summary>
        /// 异步删除立即保存
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public Task<int> DeleteNowAsync(TEntity entity)
        {
            return Task.FromResult(DeleteNow(entity));
        }
        /// <summary>
        /// 异步删除数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public Task DeleteAsync(TEntity entity)
        {
            Delete(entity);
            return Task.CompletedTask;
        }
        /// <summary>
        /// 删除立即保存
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int DeleteNow(TEntity entity)
        {
            Delete(entity);
            return SaveChanges();
        }   
        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="entity"></param>
        public void Delete(TEntity entity)
        {
            Entities.Remove(entity);
        }

        /// <summary>
        /// 异步批量删除立即保存
        /// </summary>
        /// <param name="entityParams"></param>
        /// <returns></returns>
        public Task<int> DeleteRangeNowAsync( IEnumerable<TEntity> entityParams)
        {
            return Task.FromResult(DeleteRangeNow(entityParams));
        }
        /// <summary>
        /// 批量删除立即保存
        /// </summary>
        /// <param name="entityParams"></param>
        /// <returns></returns>
        public int DeleteRangeNow(IEnumerable<TEntity> entityParams)
        {
            DeleteRange(entityParams);
            return SaveChanges();
        }
        /// <summary>
        /// 批量删除数据
        /// </summary>
        /// <param name="entityParams"></param>
        public void DeleteRange(IEnumerable<TEntity> entityParams)
        {
            Entities.RemoveRange(entityParams);
        }
        /// <summary>
        /// 按条件异步删除数据
        /// </summary>
        /// <param name="exp"></param>
        /// <returns></returns>
        public  Task<int> ExecuteDeleteAsync(Expression<Func<TEntity, bool>> exp)
        {
            return Entities.Where(exp).ExecuteDeleteAsync();
        }
        /// <summary>
        /// 按条件删除数据
        /// </summary>
        /// <param name="exp"></param>
        /// <returns></returns>
        public int ExecuteDelete(Expression<Func<TEntity, bool>> exp)
        {
            return Entities.Where(exp).ExecuteDelete();
        }
    }
}
